/**
 * MIT License
 * 
 * Copyright (c) 2024 - present @ ebraid
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */


#include <config.h>
#include <types.h>
#include <kernel/initcall.h>
#include <drivers/irq.h>
#include <pthread.h>
#include <mm/mem.h>
#include <irqnum.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>


char uart_recv_char = 0;


struct eb_irq {
    void *(*thread_fun)(void*);
    void (*handler)(void *data);
    pthread_t thread;
    void *data;
    int status;
};


static struct eb_irq eb_irq_table[CONFIG_IRQTABLE_SIZE];


static void *uatr_thread(void *arg)
{
    struct eb_irq *uart = &eb_irq_table[UART_IRQNUM];
    while(1) {
        while(uart->status == 0) {
            usleep(1000);
        }

        uart_recv_char = getchar();
        uart->handler(uart->data);
    };
}


static struct eb_irq eb_irq_table[CONFIG_IRQTABLE_SIZE] = {
    [UART_IRQNUM] = {
        .thread_fun = uatr_thread,
        .handler = NULL,
        .data = NULL,
        .status = 0,
    },
};


int irq_request(uint32_t irq, irq_handler_t handler, void *data)
{
    if(eb_irq_table[irq].status) {
        return -1;
    }

    if(eb_irq_table[irq].thread_fun == NULL) {
        return -1;
    }

    eb_irq_table[irq].status = 0;
    eb_irq_table[irq].handler = handler;
    eb_irq_table[irq].data = data;

    return pthread_create(&eb_irq_table[irq].thread, NULL, eb_irq_table[irq].thread_fun, NULL);
}


void irq_free(uint32_t irq)
{
    if(eb_irq_table[irq].status) {
        eb_irq_table[irq].status = 0;
        pthread_join(eb_irq_table[irq].thread, NULL);
    }
}


void irq_enable(uint32_t irq)
{
    eb_irq_table[irq].status = 1;
}


void irq_disable(uint32_t irq)
{
    eb_irq_table[irq].status = 0;
}


void irq_clear_flag(unsigned long arg)
{
    // do nothing
}
